﻿using System;
using System.Windows.Forms;
using Windows.Devices.Bluetooth;
using Windows.Devices.Enumeration;

namespace BLE_Assistant
{
	public partial class frmMain : Form
	{
		DeviceWatcher deviceWatcher = null;
        BluetoothLEDevice device = null;

        public frmMain()
		{
			InitializeComponent();
            //Control.CheckForIllegalCrossThreadCalls = false;
		}

		public void start_ble_search()
		{
			string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };

			deviceWatcher =
				DeviceInformation.CreateWatcher(
					BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
					requestedProperties,
					DeviceInformationKind.AssociationEndpoint);

			deviceWatcher.Added += Watcher_DeviceAdded;
            deviceWatcher.Stopped += Watcher_Stopped;
            deviceWatcher.Updated += Watcher_DeviceUpdated;
            deviceWatcher.Removed += Watcher_DeviceRemoved;

            deviceWatcher.Start();
            Console.WriteLine("seraching start...");
        }

        static bool IsWatcherStarted(DeviceWatcher watcher)
        {
            return (watcher.Status == DeviceWatcherStatus.Started) ||
                (watcher.Status == DeviceWatcherStatus.EnumerationCompleted);
        }

        private void Watcher_Stopped(DeviceWatcher sender, object args)
        {
            Console.WriteLine("seraching stop");
            
            if (InvokeRequired) {
                Invoke(new Action(() => {
                    buttonStartScanDevices.Enabled = true;
                }));
            }
        }

        private void Watcher_DeviceAdded(DeviceWatcher sender, DeviceInformation deviceInfo)
        {
            if (IsWatcherStarted(sender)) {
                ListViewItem item = new ListViewItem();
                string mac = deviceInfo.Id.Split('-')[1];

                //Console.WriteLine(deviceInfo.Id);
                if (InvokeRequired) {
                    Invoke(new Action(() => {
                        if (!is_duplicate(mac)) {
                            item.Checked = deviceInfo.Pairing.CanPair;
                            item.SubItems.Add(deviceInfo.Name);
                            item.SubItems.Add(mac);
                            item.SubItems.Add(deviceInfo.Id);
                            listViewDeviceLists.Items.Add(item);
                        }
                    }));
                }
            }
        }

        private bool is_duplicate(string mac)
        {
            foreach(ListViewItem item in listViewDeviceLists.Items) {
                if (item.SubItems[2].Equals(mac)) {
                    return true;
                }
            }

            return false;
        }

        private void Watcher_DeviceUpdated(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
        {
            // Watcher may have stopped while we were waiting for our chance to run.
            if (IsWatcherStarted(sender))
            {
                // Find the corresponding updated DeviceInformation in the collection and pass the update object
                // to the Update method of the existing DeviceInformation. This automatically updates the object
                // for us.
                //foreach (DeviceInformationDisplay deviceInfoDisp in resultCollection)
                //{
                //    if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                //    {
                //        deviceInfoDisp.Update(deviceInfoUpdate);
                //        RaiseDeviceChanged(sender, deviceInfoUpdate.Id);
                //        break;
                //    }
                //}
            }
        }

        private void Watcher_DeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
        {
            // Watcher may have stopped while we were waiting for our chance to run.
            if (IsWatcherStarted(sender))
            {
                // Find the corresponding DeviceInformation in the collection and remove it
                //foreach (DeviceInformationDisplay deviceInfoDisp in resultCollection)
                //{
                //    if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                //    {
                //        resultCollection.Remove(deviceInfoDisp);
                //        break;
                //    }
                //}

                //RaiseDeviceChanged(sender, deviceInfoUpdate.Id);
            }
        }

        private void buttonStartScanDevices_Click(object sender, EventArgs e)
        {
            listViewDeviceLists.Items.Clear();
            buttonStartScanDevices.Enabled = false;
            start_ble_search();
        }

        private void buttonConnect2Device_Click(object sender, EventArgs e)
        {
            connect_to_ble_device();
        }

        private void connect_to_ble_device() {
            try {
                device = BluetoothLEDevice.FromIdAsync(listViewDeviceLists.SelectedItems[0].SubItems[3].Text);
            } catch {
                //
            }
        }
    }
}
